package band.wukong.practice.webservice.kh.sample08;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @author wukong(wukonggg@139.com)
 */
public class UserDao {

    private static final Logger logger = LoggerFactory.getLogger(UserDao.class);
    private static final Map<String, User> users = new HashMap<>();
    private static UserDao dao = null;

    private UserDao() {
        users.put("admin", new User("admin", "nwims666"));
    }

    public static UserDao newInstance() {
        if (null == dao) {
            dao = new UserDao();
        }
        return dao;
    }

    public void add(User user) throws UserException {
        if (users.containsKey(user.getName()))  throw new UserException("用户已存在");

        users.put(user.getName(), user);
        logger.debug("user = " + user);
    }

    public void delete(String name) {
        users.remove(name);
        logger.debug("name = " + name);
    }

    public List<User> list() {
        Set<String> keys = users.keySet();
        List<User> list = new ArrayList<>();
        for (String key : keys) {
            list.add(users.get(key));
        }

        logger.debug("list.size() = " + list.size());
        return list;
    }

    public User queryByName(String name) {
        return users.get(name);
    }

    public User login(String name, String passwd) throws UserException {
        if (!users.containsKey(name))   throw new UserException("用户不存在");

        User user = users.get(name);
        if (!passwd.equals(user.getPasswd()))   throw new UserException("密码不正确");

        logger.debug("user = " + user);
        return user;
    }
}
